package jxc.servlet.user;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.base.security.Encrypt;
import eu.log.LogFactory;
import eu.log.Logger;

import jxc.data.hibernate.dao.OperatorDAO;
import jxc.data.hibernate.pojo.Operator;

/**
 * Servlet implementation class AddUser
 */
@WebServlet("/user/addUser")
public final class Add extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger log=LogFactory.getLogger("操作员管理.添加");
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Add() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		OperatorDAO dao=new OperatorDAO();
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String name=request.getParameter("name");
		String power=request.getParameter("power");
		if(username==null||username.length()<3){
			request.setAttribute("message", "用户名至少 3 个字符");
			request.getRequestDispatcher("/user/addUser.jsp").forward(request,response);
			return;
		}
		if(password==null||password.length()<6){
			request.setAttribute("message", "密码至少 6 个字符");
			request.getRequestDispatcher("/user/addUser.jsp").forward(request,response);
			return;
		}
		if(dao.getByUsername(username)!=null){
			request.setAttribute("message", "用户已经存在");
			request.getRequestDispatcher("/user/addUser.jsp").forward(request,response);
			return;
		}
		dao.save(new Operator(username,Encrypt.md5(password),name,power));
		dao.commit();
		log.notice("添加用户["+username+"]");
		request.setAttribute("message", "添加用户成功");
		request.getRequestDispatcher("/user/addUser.jsp").forward(request,response);
	}

}
